package br.com.localab.reserva.modelo;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Expression;

public class RepositorioReserva implements IRepositorioReserva, Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Session s;
	
	public RepositorioReserva(Session s) {
		this.s = s;
	}
	
	public void cadastrarReserva(Reserva reserva) throws ReservaJaCadastradoException{
		try{
			s.save(reserva);
		}catch(Exception e){
		  throw	new ReservaJaCadastradoException(reserva.getReserva_PK().getEquipamento().getNome());
		}
	}
	
	public void editarReserva(Reserva reserva) throws ReservaNaoEncontradoException{
		try{
			s.update(reserva);
		}catch(Exception e){
		  throw	new ReservaNaoEncontradoException(reserva.getReserva_PK().getEquipamento().getNome());
		}
	}
	
	public Reserva procurar(Reserva_PK reserva_PK) throws ReservaNaoEncontradoException{
		Reserva reserva;
		try{
			reserva  = (Reserva) s.load(Reserva.class, reserva_PK);
		return reserva;
		}catch(Exception e){
			throw new ReservaNaoEncontradoException(reserva_PK.getEquipamento().getNome());
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Reserva> listar(){
		return s.createCriteria(Reserva.class).list();
	}
	
	@SuppressWarnings("unchecked")
	public List<Reserva> list(String nomeCampo, boolean valorCampo) {
		Criteria c = s.createCriteria(Reserva.class);
		c.add(Expression.eq(nomeCampo, valorCampo));
		c.setCacheable(false);
		return c.list();
	}
	
	public Reserva procurar(String nomeCampo, String valorCampo) throws ReservaNaoEncontradoException{
		try{
		Criteria c = s.createCriteria(Reserva.class);
		c.add(Expression.eq(nomeCampo, valorCampo));
		c.setCacheable(true);
		Reserva reserva = (Reserva) c.uniqueResult();
		System.out.println(reserva.getReserva_PK().getEquipamento().getNome());
		return reserva;
		}catch(Exception e){
			throw new ReservaNaoEncontradoException(valorCampo);
		}
	}

	@Override
	public void removerReserva(
			Reserva reserva)
			throws ReservaNaoEncontradoException {
		try{
			s.delete(reserva);
		}catch(Exception e){
		  throw	new ReservaNaoEncontradoException(reserva.getReserva_PK().getEquipamento().getNome());
		}
		
	}
	
}
